package cn.kongwg.controller;

import com.alibaba.fastjson.JSON;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @author kongwg
 * @create 2021-03-08 23:37
 */
@RestController
@RequestMapping("/test")
public class TestController {


    @GetMapping("/test/t1")
    public String test() {

        String str = JSON.toJSONString("wo shi Sichuan");
        return str;
    }

    @GetMapping("/dow")
    public String download(HttpServletResponse response) {

        FileInputStream fis = null;
        ServletOutputStream sos = null;
        try {
            String fileName = "孔.png";

            response.reset();
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");

            response.setHeader("Content-Disposition", "attachment;fileName=" +
                    URLEncoder.encode(fileName, "UTF-8"));

            fis = new FileInputStream("F:/upload/" + fileName);

            sos = response.getOutputStream();

            IOUtils.copy(fis, sos);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (sos != null) {
                try {
                    sos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }


        return "seccess";
    }

    @PostMapping("/up")
    public String uploadload(@RequestParam("file") CommonsMultipartFile file) {

        String filename = file.getOriginalFilename();

        File realPath = new File("F:/upload");

        if (!realPath.exists()) {
            realPath.mkdir();
        }

        try {
            file.transferTo(new File(realPath + filename));
        } catch (IOException e) {
            e.printStackTrace();
        }


        return "seccess";
    }

}
